from django import forms
from .models import DataSource, Field, Table

class DataSourceForm(forms.ModelForm):
    class Meta:
        model = DataSource
        fields = ['name', 'engine', 'user', 'password', 'host', 'port', 'description']

    def clean_name(self):
        name = self.cleaned_data['name']
        qs = DataSource.objects.filter(name=name)
        if self.instance.pk:
            qs = qs.exclude(pk=self.instance.pk)
        if qs.exists():
            raise forms.ValidationError("该名称已存在。")
        return name
    
class TableForm(forms.ModelForm):
    class Meta:
        model = Table
        fields = ['name', 'description', 'data_source']

class FieldForm(forms.ModelForm):
    class Meta:
        model = Field
        fields = ['name', 'field_type', 'description', 'is_required']
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 自定义表单字段样式
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'    
